package com.ctgu.server.service.impl;

import com.ctgu.server.dao.dto.AttendanceGroupDto;
import com.ctgu.server.dao.entity.AttendanceGroup;
import com.ctgu.server.dao.entity.AttendanceGroupUser;
import com.ctgu.server.dao.entity.GroupUser;
import com.ctgu.server.dao.entity.User;
import com.ctgu.server.dao.vo.Result;
import com.ctgu.server.mapper.AttendanceGroupMapper;
import com.ctgu.server.mapper.GroupUserMapper;
import com.ctgu.server.service.AttendanceGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.server.utils.ResultUtil;
import com.github.dozermapper.core.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ctgu
 * @since 2023-06-13
 */
@Service
public class AttendanceGroupServiceImpl extends ServiceImpl<AttendanceGroupMapper, AttendanceGroup> implements AttendanceGroupService {
    @Autowired
    private Mapper mapper;

    @Autowired
    private AttendanceGroupUserServiceImpl attendanceGroupUserService;
    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private GroupUserMapper groupUserMapper;


    @Override
    @Transactional
    public Result createClockGroup(AttendanceGroupDto attendanceGroupDto) {
        User user= userService.selectUser(attendanceGroupDto.getUserId());
        if(user==null){
            return ResultUtil.error("用户不存在！");
        }
        AttendanceGroup attendanceGroup= mapper.map(attendanceGroupDto, AttendanceGroup.class);
        this.save(attendanceGroup);
        //给与创建者管理员权限

        AttendanceGroupUser attendanceGroupUser=new AttendanceGroupUser();
        attendanceGroupUser.setGroupId(attendanceGroup.getId());
        attendanceGroupUser.setIs_join_attendance(true);
        attendanceGroupUser.setIs_admin(true);
        attendanceGroupUser.setUserId(attendanceGroup.getUserId());
//        attendanceGroupUser.setUserName(attendanceGroupUser.getUserName());
        attendanceGroupUserService.save(attendanceGroupUser);
        //将目标组织加入考勤组
        List<String> userIDList= groupUserMapper.selectUserToAtt(attendanceGroupDto.getGroupIDList());
        attendanceGroupUser.setIs_admin(false);
        for(String id :userIDList ){
            attendanceGroupUser.setUserId(id);
            attendanceGroupUserService.save(attendanceGroupUser);
        }
        return ResultUtil.success();
    }
}
